import { reactive, computed, toRefs } from 'vue'
import { fetchSMSCaptcha } from '@/api'

/**
 * 发送短信验证码
 * @param duration 发送短信验证码间隔时间 默认60s
 */
export function useSMSCaptcha(duration = 60) {
  const state = reactive({
    captchaText: '获取验证码',
    captcha: '',
    countdown: duration,
    phoneNumber: ''
  })
  let countdownTimer

  const disabled = computed(
    () => state.countdown !== duration && state.countdown > 0
  )

  /**
   * 获取短信验证码
   */
  function getSMSCaptcha() {
    if (disabled.value) return void 0
    const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    const flag = phoneReg.test(state.phoneNumber)
    if (flag) {
      fetchSMSCaptcha(state.phoneNumber).then(res => {
        // state.captcha = res
        state.countdown--
        state.captchaText = state.countdown + '秒'
        countdownTimer = setInterval(() => {
          if (state.countdown > 0) {
            state.countdown--
            state.captchaText = state.countdown + '秒'
          } else {
            clearInterval(countdownTimer)
            state.countdown = duration
            state.captchaText = '重新获取'
          }
        }, 1000)
        uni.showToast({ title: '已发送验证码', icon: 'none' })
      })
    } else uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
  }

  function resetState() {
    state.captcha = ''
    state.phoneNumber = ''
    state.countdown = duration
    state.captchaText = '获取验证码'
    clearInterval(countdownTimer)
  }

  return {
    getSMSCaptcha,
    resetState,
    disabled,
    ...toRefs(state)
  }
}
